<%@ Page Language="C#" MasterPageFile="~/Site.master" Title="GridView Complex Editing" %>
<%@ Import namespace = "System.Text" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
    <script runat="server">
        protected override void OnPreRender(EventArgs e)
        {
            Supplier[] suppliers = null;
            Category[] categories = null;

            using (DataService svc = new DataService())
            {
                suppliers = svc.GetAllSupplier();
                categories = svc.GetAllCategory();
            }

            ((GridViewDropDownListColumn)this.GridView1.Columns[2]).DataSource = categories;
            ((GridViewDropDownListColumn)this.GridView1.Columns[3]).DataSource = suppliers;

            base.OnPreRender(e);
        }
    </script>
    <h3>Product Information</h3>
    <table>
        <tr>
            <td style="text-align:left">
                <AjaxData:GridView ID="GridView1" runat="server" CssClass="DataWebControlStyle" 
                CellSpacing="0" CellPadding="3" DataKeyName="ID" SortColumn="Name" SortOrderAscendingImageUrl="~/Images/up.gif" 
                SortOrderDescendingImageUrl="~/Images/dn.gif" SortCommandEvent="onSortCommand" 
                EditCommandEvent="onEditCommand" DeleteCommandEvent="onDeleteCommand" 
                UpdateCommandEvent="onUpdateCommand" CancelCommandEvent="onCancelCommand" DataBoundEvent="onDataBound">
                   <AlternatingRowStyle CssClass="AlternatingRowStyle" />
                   <RowStyle CssClass="RowStyle"/>
                   <HeaderStyle CssClass="HeaderStyle"/>
                   <Columns>
                        <AjaxData:GridViewCommandColumn ButtonType="Image" ShowEditButton="true" ShowDeleteButton="true" ShowCancelButton="true" EditImageUrl="~/Images/edit.gif" DeleteImageUrl="~/Images/delete.gif" UpdateImageUrl="~/Images/update.gif" CancelImageUrl="~/Images/cancel.gif" HeaderStyle-Wrap="false" ItemStyle-Wrap="false"/>
                        <AjaxData:GridViewBoundColumn HeaderText="Product" DataField="Name" SortField="Name" 
                        HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false" AllowDragAndDrop="true"/>
                        <AjaxData:GridViewDropDownListColumn HeaderText="Category" HeaderStyle-HorizontalAlign="Left"
                            ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false" SortField="CategoryName"
                            DropDownListDataText="Name" DropDownListDataValue="ID" DataField="CategoryID" AllowDragAndDrop="true" />
                        <AjaxData:GridViewDropDownListColumn HeaderText="Supplier" HeaderStyle-HorizontalAlign="Left"
                            ItemStyle-HorizontalAlign="Left" HeaderStyle-Wrap="false" SortField="SupplierName"
                            DropDownListDataText="Company" DropDownListDataValue="ID" DataField="SupplierID" AllowDragAndDrop="true" />
                        <AjaxData:GridViewBoundColumn HeaderText="Price" DataField="UnitPrice" DataFormatString="c" SortField="UnitPrice" ReadOnly="true" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="right" HeaderStyle-Wrap="false"/>
                        <AjaxData:GridViewCheckBoxColumn HeaderText="Discontinued" DataField="Discontinued" SortField="Discontinued" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Center" HeaderStyle-Wrap="false"/>
                   </Columns>
                </AjaxData:GridView>
            </td>
        </tr>
        <tr>
            <td style="text-align:right">
                <AjaxData:Pager ID="Pager1" runat="server" CssClass="PagerRowStyle" CurrentPageStyle-CssClass="PagerCurrentPage" OtherPageStyle-CssClass="PagerOtherPage" PageChangedEvent="pageChanged"></AjaxData:Pager>
            </td>
        </tr>
    </table>
    <script type="text/javascript">

        var _gridView;
        var _pager;

        var _products;

        function pageLoad(sender, e)
        {
            _gridView = GridView1;
            _pager = Pager1;
            loadProducts();
        }

        function loadProducts()
        {
            //Need to convert the sortoder so our WS understand
            var sortColumn = _gridView.get_sortColumn();
            var sortOrder = (_gridView.get_sortOrder() == AjaxDataControls.GridViewSortOrder.Descending) ? 'DESC' : 'ASC';
            var startIndex = (_pager.get_pageIndex() * _pager.get_pageSize());
            DataService.GetProductList(startIndex, _pager.get_pageSize(), sortColumn, sortOrder, onLoadSuccess);
        }

        function onLoadSuccess(result)
        {
            _products = result.Rows;
            _pager.set_recordCount(result.Total);
            bindProducts();
        }

        function bindProducts()
        {
            _gridView.set_dataSource(_products);
            _gridView.dataBind();
        }
        function onSortCommand(sender, e)
        {
            _gridView.set_sortColumn(e.get_sortColumn())
            _gridView.set_sortOrder(e.get_sortOrder());
            _pager.set_pageIndex(0); // need to reset the current page as sorting is changed
            _gridView.set_editIndex(-1);
            loadProducts();
        }

        function onEditCommand(sender, e)
        {
            _gridView.set_editIndex(e.get_row().get_rowIndex());
        }

        function onDeleteCommand(sender, e)
        {
            if (confirm('Are you sure you want to delete this product?'))
            {
                var productId = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];

                DataService.DeleteProduct(
                                            productId,
                                            function(result)
                                            {
                                                if (result == true)
                                                {
                                                    _gridView.set_editIndex(-1);
                                                    loadProducts();
                                                }
                                            }
                                          );
            }
        }

        function onUpdateCommand(sender, e)
        {
            var row = e.get_row();
            var productId = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];

            // Since we support drag and drop the column index may vary, so get the current index first.
            var txtProduct = row.getCellByColumnDataField('Name');
            var chkDiscontinued = row.getCellByColumnDataField('Discontinued');
            var ddlCategory = row.getCellByColumnDataField('CategoryID');
            var ddlSupplier = row.getCellByColumnDataField('SupplierID');

            var product = e.get_row().get_dataItem();

            product.Name = txtProduct.value.trim();
            product.CategoryID = ddlCategory.get_selectedValue();

            if (product.CategoryID < 1)
            {
                product.CategoryName = '';
            }
            else
            {
                product.CategoryName = ddlCategory.get_selectedText();
            }

            product.SupplierID = ddlSupplier.get_selectedValue();

            if (product.SupplierID < 1)
            {
                product.SupplierName = '';
            }
            else
            {
                product.SupplierName = ddlSupplier.get_selectedText();
            }

            product.Discontinued = chkDiscontinued.checked;

            DataService.UpdateProduct(
                                        productId,
                                        product.Name,
                                        product.CategoryID,
                                        product.SupplierID,
                                        product.Discontinued,
                                        function(result) 
                                        {
                                            if (result == true) 
                                                _gridView.set_editIndex(-1);
                                        }
            );
        }             

        function onCancelCommand(sender, e)
        {
            _gridView.set_editIndex(-1);
        }

        function pageChanged(sender, e)
        {
            _pager.set_pageIndex(e.get_newPageIndex());
            _gridView.set_editIndex(-1);
            loadProducts();
        }
        
        
        function onDataBound(sender,e)
        {
            var editIndex = _gridView.get_editIndex();
            if (editIndex != -1)
            {
                var rows = _gridView.get_rows();
                var tr = rows[editIndex].get_container();
                var input = tr.getElementsByTagName("input");
                if (input)
                {
                    if (input[0].type == "text")
                    {
                        input[0].focus();
                    }
                }
            }
        }
        
    </script>
</asp:Content>